using Gtk;
using Npgsql;
using System;

namespace PTransaction
{


	public partial class TransactionView : Gtk.Window
	{
		private NpgsqlConnection connection;
		private NpgsqlTransaction transaction;

		public TransactionView () : base(Gtk.WindowType.Toplevel)
		{
			this.Build ();
			
			
			connection = DbConnection.Instance.Connection;
			
			//prueba();
			
			goForwardAction.Activated += delegate {
				transaction = connection.BeginTransaction();
				labelStatus.LabelProp = "BeginTransaction";
			};
			
			executeAction.Activated += delegate {
				string sql = textView.Buffer.Text;
				NpgsqlCommand command = connection.CreateCommand();
				command.CommandText = sql;
				command.CommandTimeout = 0;
				try {
					command.ExecuteNonQuery();
					labelStatus.LabelProp = "Command OK";
				} catch (Exception e) {
					MessageDialog messageDialog = new MessageDialog(null, DialogFlags.Modal, 
						MessageType.Error, ButtonsType.Ok, e.Message);		
					messageDialog.Run();
					messageDialog.Destroy();
				}
			};
			
			applyAction.Activated += delegate {
				transaction.Commit();
				labelStatus.LabelProp = "Commit";
			};
			
			cancelAction.Activated += delegate {
				transaction.Rollback();
				labelStatus.LabelProp = "Rollback";
			};
		}
		
		private void prueba()
		{
			transaction = DbConnection.Instance.Connection.BeginTransaction();
			try {
				NpgsqlCommand command1 = DbConnection.Instance.Connection.CreateCommand();
				command1.CommandText = "update articulo set precio=precio+0.1 where id = 1";
				command1.ExecuteNonQuery();
				
				NpgsqlCommand command2 = DbConnection.Instance.Connection.CreateCommand();
				command2.CommandText = "update articulo set precio=precio-0.1 where id = 2000";
				if (command2.ExecuteNonQuery() != 1)
					throw new Exception("No existe artículo con el id=2000");
				
				transaction.Commit();
			} catch (Exception e) {
				transaction.Rollback();
				MessageDialog messageDialog = new MessageDialog(null, DialogFlags.Modal, 
					MessageType.Error, ButtonsType.Ok, e.Message);		
				messageDialog.Run();
				messageDialog.Destroy();
			}
		}
	}
}
